const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const { NodeSSH } = require('node-ssh');

let mainWindow;
let sshConnections = new Map();

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1400,
    height: 900,
    minWidth: 1000,
    minHeight: 700,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    },
    title: 'Linux服务器间文件传输工具 - Server to Server File Transfer'
  });

  mainWindow.loadFile('index.html');
  
  // 开发时打开开发者工具
  if (process.env.NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools();
  }
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  // 关闭所有SSH连接
  sshConnections.forEach(connection => {
    if (connection && connection.ssh && typeof connection.ssh.dispose === 'function') {
      connection.ssh.dispose();
    }
  });
  sshConnections.clear();
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// SSH连接处理
ipcMain.handle('ssh-connect', async (event, config, panelId) => {
  try {
    const ssh = new NodeSSH();
    await ssh.connect({
      host: config.host,
      username: config.username,
      password: config.password,
      port: config.port || 22,
      tryKeyboard: true,
      onKeyboardInteractive: (name, instructions, instructionsLang, prompts, finish) => {
        if (prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password')) {
          finish([config.password]);
        }
      }
    });
    
    const connectionId = `${panelId}_${config.host}_${config.username}_${Date.now()}`;
    sshConnections.set(connectionId, {
      ssh,
      config: {
        ...config,
        panelId
      }
    });
    
    return { success: true, connectionId };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 获取所有活跃连接
ipcMain.handle('get-active-connections', async () => {
  const connections = [];
  sshConnections.forEach((value, key) => {
    connections.push({
      id: key,
      host: value.config.host,
      username: value.config.username,
      panelId: value.config.panelId
    });
  });
  return { success: true, connections };
});

// 获取远程文件列表
ipcMain.handle('ssh-list-files', async (event, connectionId, remotePath) => {
  try {
    const connection = sshConnections.get(connectionId);
    if (!connection) {
      throw new Error('SSH连接不存在');
    }

    const result = await connection.ssh.execCommand(`ls -la "${remotePath}" 2>/dev/null || echo "DIRECTORY_NOT_FOUND"`);
    
    if (result.stdout.includes('DIRECTORY_NOT_FOUND')) {
      return { success: false, error: '目录不存在' };
    }

    const lines = result.stdout.split('\n').filter(line => line.trim());
    const files = [];
    
    for (let i = 1; i < lines.length; i++) { // 跳过第一行总计信息
      const line = lines[i];
      const parts = line.split(/\s+/);
      if (parts.length >= 9) {
        const permissions = parts[0];
        const size = parts[4];
        const date = `${parts[5]} ${parts[6]} ${parts[7]}`;
        const name = parts.slice(8).join(' ');
        
        if (name !== '.' && name !== '..') {
          files.push({
            name,
            size,
            date,
            isDirectory: permissions.startsWith('d'),
            permissions
          });
        }
      }
    }
    
    return { success: true, files, currentPath: remotePath };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 服务器间文件传输
ipcMain.handle('transfer-between-servers', async (event, sourceConnectionId, targetConnectionId, sourceFilePath, targetFilePath, fileName) => {
  try {
    const sourceConnection = sshConnections.get(sourceConnectionId);
    const targetConnection = sshConnections.get(targetConnectionId);
    
    if (!sourceConnection || !targetConnection) {
      throw new Error('源服务器或目标服务器连接不存在');
    }

    // 创建临时目录
    const tempDir = path.join(require('os').tmpdir(), 'filetransfer');
    if (!fs.existsSync(tempDir)) {
      fs.mkdirSync(tempDir);
    }
    
    const tempFilePath = path.join(tempDir, fileName);
    
    // 步骤1：从源服务器下载文件到临时目录
    await sourceConnection.ssh.getFile(tempFilePath, sourceFilePath);
    
    // 步骤2：从临时目录上传文件到目标服务器
    await targetConnection.ssh.putFile(tempFilePath, targetFilePath);
    
    // 步骤3：清理临时文件
    if (fs.existsSync(tempFilePath)) {
      fs.unlinkSync(tempFilePath);
    }
    
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 上传文件（保留本地上传功能）
ipcMain.handle('ssh-upload-file', async (event, connectionId, localPath, remotePath) => {
  try {
    const connection = sshConnections.get(connectionId);
    if (!connection) {
      throw new Error('SSH连接不存在');
    }

    await connection.ssh.putFile(localPath, remotePath);
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 下载文件（保留本地下载功能）
ipcMain.handle('ssh-download-file', async (event, connectionId, remotePath, localPath) => {
  try {
    const connection = sshConnections.get(connectionId);
    if (!connection) {
      throw new Error('SSH连接不存在');
    }

    await connection.ssh.getFile(localPath, remotePath);
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 创建远程目录
ipcMain.handle('ssh-create-directory', async (event, connectionId, remotePath) => {
  try {
    const connection = sshConnections.get(connectionId);
    if (!connection) {
      throw new Error('SSH连接不存在');
    }

    await connection.ssh.execCommand(`mkdir -p "${remotePath}"`);
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 删除远程文件/目录
ipcMain.handle('ssh-delete', async (event, connectionId, remotePath, isDirectory) => {
  try {
    const connection = sshConnections.get(connectionId);
    if (!connection) {
      throw new Error('SSH连接不存在');
    }

    const command = isDirectory ? `rm -rf "${remotePath}"` : `rm "${remotePath}"`;
    await connection.ssh.execCommand(command);
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 获取本地文件列表（保留备用）
ipcMain.handle('get-local-files', async (event, localPath) => {
  try {
    const files = [];
    const items = fs.readdirSync(localPath, { withFileTypes: true });
    
    for (const item of items) {
      const fullPath = path.join(localPath, item.name);
      const stats = fs.statSync(fullPath);
      
      files.push({
        name: item.name,
        size: stats.size.toString(),
        date: stats.mtime.toLocaleString(),
        isDirectory: item.isDirectory(),
        fullPath
      });
    }
    
    return { success: true, files, currentPath: localPath };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 选择本地目录（保留备用）
ipcMain.handle('select-local-directory', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  });
  
  if (!result.canceled && result.filePaths.length > 0) {
    return { success: true, path: result.filePaths[0] };
  }
  
  return { success: false };
});

// 断开SSH连接
ipcMain.handle('ssh-disconnect', async (event, connectionId) => {
  try {
    const connection = sshConnections.get(connectionId);
    if (connection) {
      connection.ssh.dispose();
      sshConnections.delete(connectionId);
    }
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 获取服务器信息
ipcMain.handle('get-server-info', async (event, connectionId) => {
  try {
    const connection = sshConnections.get(connectionId);
    if (!connection) {
      throw new Error('SSH连接不存在');
    }

    const result = await connection.ssh.execCommand('uname -a && df -h / && free -h');
    return { success: true, info: result.stdout };
  } catch (error) {
    return { success: false, error: error.message };
  }
}); 